document.write('<script src="/static_h/js/cos-js-sdk-v5.min.js"></script>');
var script = document.createElement('script'); //创建script标签节点
script.setAttribute('type', 'text/javascript'); //设置script类型
script.setAttribute('src', 'https://www.layuicdn.com/layui/layui.js'); //设置js地址
document.body.appendChild(script); //将js追加为body的子标签
//判断script1是否加载成功
script.onload = function (obj) {
    if (!script.readyState || script.readyState == 'loaded' || script.readyState == 'complete') {
        layui.extend({
            md5: "/config/lib/md5", // 系统扩展
        }).use(['form', 'upload', 'element', 'md5'], function () {
            var $ = layui.jquery,
                md5 = layui.md5,
                upload = layui.upload;
            var element = layui.element;
            var pathname = '/system';
            layui.link('https://www.layuicdn.com/layui/css/layui.css');
            $('#pupload').html(`<div class="layui-input-inline" style="position: fixed;margin-top: -28px;right: 22px;z-index: 99999;">
        <button type="button" class="layui-btn layui-btn-sm layui-btn-primary videoBtn">大视频上传</button>
    </div>
    <div class="layui-input-inline">
        <span id="seccess"></span>
    </div>
    <div class="layui-form-item">
        <div class="layui-progress layui-progress-big" lay-showpercent="true" lay-filter="uploadProgress"
            style="display: none;">
            <div class="layui-progress-bar layui-bg-red" lay-percent="0%"></div>
        </div>
    </div>`);
            //拖拽上传
            upload.render({
                elem: '.videoBtn',
                auto: false,
                accept: 'video', //视频
                exts: 'mp4', //
                choose: function (obj) {
                    $('[lay-filter="uploadProgress"]').show();
                    element.progress('uploadProgress', '0%'); //设置页面进度
                    obj.preview(function (index, file, result1) {
                        multipleUpload(file);
                    });

                }
            });

            function multipleUpload(file) {
                var cos = new COS({
                    // 必选参数
                    getAuthorization: function (options, callback) {
                        $.get(pathname + "/Attachment/getSign", {
                            // 可从 options 取需要的参数
                        }, function (res) {
                            let data = res.data;
                            var credentials = data && data.credentials;
                            if (!data || !credentials) return console.error('credentials invalid');
                            callback({
                                TmpSecretId: credentials.tmpSecretId,
                                TmpSecretKey: credentials.tmpSecretKey,
                                SecurityToken: credentials.sessionToken,
                                // 建议返回服务器时间作为签名的开始时间，避免用户浏览器本地时间偏差过大导致签名错误
                                StartTime: data.startTime, // 时间戳，单位秒，如：1580000000
                                ExpiredTime: data.expiredTime, // 时间戳，单位秒，如：1580000900
                            });
                        });
                    }
                });
                let file_ext = file.name.split(".")[1];
                let type = file.type.split("/")[0];
                var timestamp = new Date().getTime();
                var storeAs = type + '/' + md5("'" + timestamp + "'") + '.' + file_ext; //设置上传的文件名
                cos.uploadFile({
                    Bucket: 'lizehua-1258912695',
                    /* 必须 */
                    Region: 'ap-beijing',
                    /* 存储桶所在地域，必须字段 */
                    Key: storeAs,
                    /* 必须 */
                    Body: file,
                    /* 必须 */
                    SliceSize: 1024 * 1024 * 5,
                    /* 触发分块上传的阈值，超过5MB使用分块上传，非必须 */
                    onTaskReady: function (taskId) {
                        /* 非必须 */
                        console.log(taskId);
                    },
                    onProgress: function (progressData) {
                        /* 非必须 */
                        // console.log(123,progressData);
                        let p = progressData.percent;
                        element.progress('uploadProgress', parseFloat(p * 100).toFixed(2) + '%');
                        if (p == 1) {
                            $("input[name='file']").val(''); //上传成功后将文件input清空**
                            $('#uploadDemoView').removeClass('layui-hide').find('video').attr('src', 'http://' + ossConfig.bucket + '.' + ossConfig.region + '.aliyuncs.com/' + storeAs);
                        }
                    },
                    onFileFinish: function (err, data, options) {
                        // console.log(err, data, options);
                        // console.log(options.Key + '上传' + (err ? '失败' : '完成'));
                    },
                }, function (err, data) {
                    if (data.statusCode != 200) {
                        return layer.msg('上传失败', {
                            icon: 5
                        });
                    }
                    let datas = {
                        name: file.name,
                        filesize: file.size,
                        url: storeAs,
                        mimetype: file.type
                    };
                    $.post(pathname + "/Attachment/split_save", datas,
                        function (res) {
                            layer.msg('上传成功');
                            $('[lay-filter="uploadProgress"]').hide();
                            $('#videoUrl').val(res.data.url);
                            createPreviewVideo(res.data.url);
                            // let str = '<video width="150" height="100" controls><source src="' + res.data.url + '" type="video/mp4">您的浏览器不支持 HTML5 video 标签。</video>';
                            // $("#seccess").html(str);
                        },
                        "json"
                    );
                });
            }
            /**
             * 根据url生成视频预览
             * @param url
             */
            function createPreviewVideo(url) {
                if (!url) return;
                if (url.startsWith("http") && url.indexOf(".mp4") > 0) {
                    $("body #preview").html('<div class="previewMsg"><span>' + lang.urlError + '</span></div>' +
                        '<video class="previewVideo"' +
                        ' src="' + url + '"' +
                        ' width="' + 420 + '"' +
                        ' height="' + 280 + '"' +
                        ' play="true" loop="false" data-setup="{}" controls="controls" preload="auto">' +
                        '</video>');
                }
                if (url.startsWith("<embed>")) {
                    $("body #preview").html('<div class="previewMsg"><span>' + lang.urlError + '</span></div>' + url);
                }
            }
        });
    }
}